package com.grade.advice;

import com.google.gson.Gson;
import com.grade.utils.Results;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Aspect
@Component
public class LoggingAdvice {
    @Autowired
    HttpSession session;
    @Autowired
    HttpServletResponse response;
    @Around(value = "execution(* com.grade.controller.*.*(..))")
    public  Object aroundMethod(ProceedingJoinPoint point){
        Object result = null;
        try {
            //权限拦截控制器所有的方法，除去 登录、验证码
            String methodName = point.getSignature().getName();
            if ("createCode".equals(methodName) || "login".equals(methodName)) {
                //调用目标方法
                result = point.proceed();
            } else {
                //获取session
                Object nowusername = session.getAttribute("usr");
                if (nowusername != null) {
                    //调用目标方法
                    result = point.proceed();
                } else {
                    //没有登录
                    Results results = new Results("403", "没有权限访问");
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(new Gson().toJson(results));
                }
            }
        } catch (Throwable e) {
            try {
                //全局异常处理
                Results results = new Results("500", "服务器开小差了");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(new Gson().toJson(results));
            } catch (IOException ex) {
            }
        } finally {
            //此处做一个用户的行为信息记录，后期方便查看
        }
        return result;

    }
}
